/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.fastaconverter.gui;

import com.compomics.fastaconverter.DNAtoAAConverter;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.net.URL;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingWorker;

/**
 *
 * @author Kenneth
 */
public class MainWindow extends javax.swing.JFrame {

    private static JDialog dialog;
    private File inputFasta;
    private File outputFasta;
    private static String includeEnabled = "";
    private Preview preview;

    /**
     * Creates new form MainWindow
     */
    public MainWindow() {
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

        initComponents();
        this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height / 2 - this.getSize().height / 2);
        minLength.setModel(new SpinnerNumberModel(15, 1, 50, 1));
    }
    private final JFileChooser inputFastaChooser = new JFileChooser();
    private final JFileChooser outputFastaChooser = new JFileChooser();

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel6 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        inputFastaTextBox = new javax.swing.JTextField();
        outputFastaTextBox = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        minLength = new javax.swing.JSpinner();
        include_shorter = new javax.swing.JCheckBox();
        btnConvert = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        inputFastaFile = new javax.swing.JButton();
        outputFastaLoader = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();

        jLabel6.setText("Input *");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("FastaConverter");
        setMaximumSize(new java.awt.Dimension(370, 200));
        setMinimumSize(new java.awt.Dimension(370, 200));
        setResizable(false);

        jLabel1.setText("Input *");

        jLabel2.setText("Output");

        inputFastaTextBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inputFastaTextBoxActionPerformed(evt);
            }
        });

        outputFastaTextBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                outputFastaTextBoxActionPerformed(evt);
            }
        });

        jLabel3.setText("Minimum length *");

        minLength.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                minLengthStateChanged(evt);
            }
        });

        include_shorter.setText("Include shorter sequences");
        include_shorter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                include_shorterActionPerformed(evt);
            }
        });

        btnConvert.setText("Convert");
        btnConvert.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConvertActionPerformed(evt);
            }
        });

        jButton1.setText("Preview");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        inputFastaFile.setText("...");
        inputFastaFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inputFastaFileActionPerformed(evt);
            }
        });

        outputFastaLoader.setText("...");
        outputFastaLoader.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                outputFastaLoaderActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
        jLabel4.setText("Compomics FastaConverter");

        jLabel5.setText("* fields are required");

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jLabel7.setText("kenneth.verheggen@ugent.be");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addComponent(jLabel2))
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(inputFastaTextBox, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(inputFastaFile, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(outputFastaTextBox, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(outputFastaLoader, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel3)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(minLength, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(jLabel5))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jButton1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(btnConvert))
                                .addComponent(include_shorter))))
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel7)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(inputFastaTextBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(inputFastaFile))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(outputFastaTextBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(outputFastaLoader)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(minLength, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(include_shorter))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnConvert)
                    .addComponent(jButton1)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnConvertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConvertActionPerformed
        String[] commandString;
        File inputFile = new File(inputFastaTextBox.getText());
        File outputFile = new File(outputFastaTextBox.getText());
        String minLengthString = "" + minLength.getValue();

        if (inputFastaTextBox.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "The input-fasta should not be blank.");
            return;
        } else if (outputFastaTextBox.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "The output-fasta should not be blank.");
            return;
        } else {
            Converter swingConverter = new Converter(inputFile, outputFile, (Integer) minLength.getValue(), include_shorter.isSelected(), this);
            try {
                swingConverter.doInBackground();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "An error has occurred...");
            }
        }


    }//GEN-LAST:event_btnConvertActionPerformed

    private void inputFastaTextBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inputFastaTextBoxActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_inputFastaTextBoxActionPerformed

    private void include_shorterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_include_shorterActionPerformed
        if (preview != null) {
            if (include_shorter.isSelected()) {
                preview.setIncludeShort(true);
            } else {
                preview.setIncludeShort(false);
            }
        }
    }//GEN-LAST:event_include_shorterActionPerformed

    private void inputFastaFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inputFastaFileActionPerformed
        int returnVal = inputFastaChooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            inputFasta = inputFastaChooser.getSelectedFile();
            inputFastaTextBox.setText(inputFasta.getAbsolutePath());
            outputFastaTextBox.setText(inputFasta.getAbsolutePath().substring(0, inputFasta.getAbsolutePath().indexOf(".")) + "_converted.fasta");
        }
    }//GEN-LAST:event_inputFastaFileActionPerformed

    private void outputFastaLoaderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_outputFastaLoaderActionPerformed
        int returnVal = outputFastaChooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            outputFasta = outputFastaChooser.getSelectedFile();
            outputFastaTextBox.setText(outputFasta.getAbsolutePath());
            // TODO add your handling code here:
        }
    }//GEN-LAST:event_outputFastaLoaderActionPerformed

    private void outputFastaTextBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_outputFastaTextBoxActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_outputFastaTextBoxActionPerformed
    public void killPreview() {
        preview = null;
    }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (preview == null) {
            this.preview = new Preview((Integer) minLength.getValue(), include_shorter.isSelected(), this);

            preview.addWindowListener(new WindowListener() {
                public void windowClosed(WindowEvent arg0) {
                    preview = null;
                }

                public void windowClosing(WindowEvent arg0) {
                    preview = null;
                }

                @Override
                public void windowOpened(WindowEvent e) {
                }

                @Override
                public void windowIconified(WindowEvent e) {
                }

                @Override
                public void windowDeiconified(WindowEvent e) {
                }

                @Override
                public void windowActivated(WindowEvent e) {
                }

                @Override
                public void windowDeactivated(WindowEvent e) {
                }
            });
        } else {
            preview.setMinLength((Integer) minLength.getValue());
            preview.setIncludeShort(include_shorter.isSelected());
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void minLengthStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_minLengthStateChanged
        if (preview != null) {
            preview.setMinLength((Integer) minLength.getValue());
        }
    }//GEN-LAST:event_minLengthStateChanged

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConvert;
    private javax.swing.JCheckBox include_shorter;
    private javax.swing.JButton inputFastaFile;
    private javax.swing.JTextField inputFastaTextBox;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JSpinner minLength;
    private javax.swing.JButton outputFastaLoader;
    private javax.swing.JTextField outputFastaTextBox;
    // End of variables declaration//GEN-END:variables

    private class Converter extends SwingWorker<Integer, String> {

        private final File input;
        private final File output;
        private final int treshold;
        private final boolean included;
        private boolean conversionDone = false;
        private Thread conversionThread;

        public Converter(File input, File output, int treshold, boolean included, JFrame mainWindow) {
            this.input = input;
            this.output = output;
            this.treshold = treshold;
            this.included = included;
        }

        public void convert() {
            final String[] commandString;
            String inputFile = input.getAbsolutePath();
            String outputFile = output.getAbsolutePath();
            String minLengthString = "" + treshold;


            if (include_shorter.isSelected()) {
                commandString = new String[]{"-input", inputFile, "-output", outputFile, "-include_unlikely_treshold", minLengthString, "-include_unlikely", "true"};
            } else {
                commandString = new String[]{"-input", inputFile, "-output", outputFile, "-include_unlikely_treshold", minLengthString};
            }
            conversionThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        DNAtoAAConverter.main(commandString);
                    } catch (Throwable e) {
                    } finally {
                        conversionDone = true;
                        dialog.dispose();
                    }
                    conversionDone = true;
                    dialog.dispose();
                }
            });
            conversionThread.start();
        }

        @Override
        protected Integer doInBackground() throws Exception {


            setProgress(1);
            convert();
            dialog = new JDialog();
            dialog.setLocationRelativeTo(null);
            dialog.setTitle("Please Wait...");
            dialog.setBackground(Color.GRAY);
            URL imageURL = new DNAtoAAConverter().getClass().getResource("/ajax-loader.gif");
            if (imageURL != null) {
                ImageIcon loading = new ImageIcon(imageURL);
                dialog.add(new JLabel("Translating fasta... ", loading, JLabel.CENTER));
            } else {
                dialog.add(new JLabel("Translating fasta... ", JLabel.CENTER));
            }
            dialog.validate();
            dialog.setSize(200, 150);
            dialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            dialog.setModalityType(ModalityType.APPLICATION_MODAL);
            dialog.setAlwaysOnTop(true);
            dialog.setResizable(false);
            dialog.pack();
            dialog.setVisible(true);

            while (!conversionDone) {
                //wait 
                Thread.sleep(500);
            }
            dialog.setVisible(false);
            return 1;
        }

        @Override
        protected void process(List< String> chunks) {
            // Messages received from the doInBackground() (when invoking the publish() method)
        }
    }
}
